package com.ytjj.qmyx.supplychain.service;

import com.ytjj.qmyx.supplychain.common.constants.DateTypeConstant;
import com.ytjj.qmyx.supplychain.common.model.response.DateResponse;
import com.ytjj.qmyx.supplychain.common.model.response.OrderStatisticResponse;
import com.ytjj.qmyx.supplychain.common.utils.CalendarUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.BankerOrderMapper;
import com.ytjj.qmyx.supplychain.mapper.OrderStatisticsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 *
 * 
 * @className BankerOrderServiceImpl
 * @since 2020/11/30 15:08
 */
@Service
public class BankerDataStatisticsService {

    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Resource
    private RedisService redisService;
    @Autowired
    private BankerService bankerService;
    @Resource
    private OrderStatisticsMapper orderStatisticsMapper;

    public List<Object> getSaleStatisticsList(String dateType) {
        DateResponse time = this.getTime(dateType);
        return this.getOrderData(dateType, time);
    }

    /**
     * 获取时间
     *
     * @return
     * @param dateType
     */
    public DateResponse getTime(String dateType) {
        Date startTime = null;
        Date endTime = null;
        DateResponse dateResponse = new DateResponse();
        LocalDate today = LocalDate.now();
        if (DateTypeConstant.DAY.equals(dateType)) {
            LocalDate yesterday = today.minusDays(1);
            startTime = CalendarUtil.dateFormatParse(yesterday);
            endTime = CalendarUtil.getEndTime(startTime);
        }
        if (DateTypeConstant.WEEK.equals(dateType)) {
            LocalDate weekDay = LocalDate.now().minusDays(DateTypeConstant.WEEK_NUM);
            startTime = CalendarUtil.dateFormatParse(weekDay);
            endTime = CalendarUtil.dateFormatParse(today);
            dateResponse.setStartDateRange(weekDay);
        }
        if (DateTypeConstant.MONTH.equals(dateType)) {
            LocalDate monthDay = LocalDate.now().minusDays(DateTypeConstant.MONTH_NUM);
            startTime = CalendarUtil.dateFormatParse(monthDay);
            endTime = CalendarUtil.dateFormatParse(today);
            dateResponse.setStartDateRange(monthDay);
        }
        dateResponse.setStartTime(startTime);
        dateResponse.setEndTime(endTime);
        dateResponse.setBankerId(bankerService.getUserInfo().getId());
        return dateResponse;
    }

    /**
     * 成交额和销售量
     *
     * @return
     */
    public List<Object> getOrderData(String dateType, DateResponse dateResponse) {
        dateResponse.setDateType(dateType);
        if (DateTypeConstant.DAY.equals(dateType)) {
            return this.getData(dateResponse, DateTypeConstant.DAY_NUM);
        }
        if (DateTypeConstant.WEEK.equals(dateType)) {
            return this.getData(dateResponse, DateTypeConstant.WEEK_NUM);
        }
        if (DateTypeConstant.MONTH.equals(dateType)) {
            return this.getData(dateResponse, DateTypeConstant.MONTH_NUM);
        }
        return Collections.emptyList();
    }

    /**
     * 获取数据
     *
     * @return
     */
    public List<Object> getData(DateResponse dateResponse, Integer num) {
        List<OrderStatisticResponse> orderDataList = null;
        if (DateTypeConstant.DAY.equals(dateResponse.getDateType())) {
            orderDataList = orderStatisticsMapper.getOrderDataByHour(dateResponse);
        } else {
            orderDataList = orderStatisticsMapper.getOrderDataByWeekAndMonth(dateResponse);
        }
        List<Object> orderList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Map orderMap = new HashMap<>();
            orderMap.put("timeCount", i + 1);
            orderMap.put("totalMoney", 0.00);
            orderMap.put("payOrderNum", 0);
            if (DateTypeConstant.DAY.equals(dateResponse.getDateType())) {
                String time = i + "";
                this.commonMap(orderMap, time, orderDataList, dateResponse.getDateType());
            } else {
                LocalDate time = dateResponse.getStartDateRange().plusDays(i);
                this.commonMap(orderMap, time, orderDataList, dateResponse.getDateType());
            }
            orderList.add(orderMap);
        }
        return orderList;
    }


    public Map commonMap(Map orderMap, Object time, List<OrderStatisticResponse> orderDataList, String dateType) {
        orderMap.put("time", time + "");
        OrderStatisticResponse orderStatisticResponse = orderDataList.stream()
                .filter(item -> item.getTime().equals(time.toString()))
                .findAny().orElse(null);
        if (orderStatisticResponse != null) {
            orderMap.put("totalMoney", orderStatisticResponse.getTotalMoney());
            orderMap.put("payOrderNum", orderStatisticResponse.getPayOrderNum());
        }
        if(DateTypeConstant.WEEK.equals(dateType)) {
            String weekTime = dateToWeek(time + "");
            orderMap.put("time", weekTime);
        }
        return orderMap;
    }


    /**
     * 根据日期获取 星期 （2019-05-06 ——> 星期一）
     * @param datetime
     * @return
     */
    public String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = f.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    public Date stringToDate(String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(time);
        return date;
    }


    /**
     * @Description 获取第二天凌晨过期的秒数
     * 
     * 
     */
    public Long getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        // 改成这样就好了
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:MM:dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取小时
     *
     * @return
     */

    public static String hourTime(String current) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("HH");
        String currentTimeStr = formatter.format(currentTime);
        return currentTimeStr;
    }


    // 判断是否是整点
    public static Boolean isClockTime(String timeString) {
        Boolean clockFlag = false;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("mm");
        String currentTimeStr = formatter.format(currentTime);
        if (currentTimeStr.equals("00")) {
            clockFlag = true;
        }
        return clockFlag;
    }


    public static void main(String[] args) {
        System.out.println(LocalDateTime.now().toString());
        System.out.println(String.format(" %s:00:00", String.format("%02d", 9)));

    }
}
